package repository

import (
	"com.haojuetrace/actualCombat/common"
	"com.haojuetrace/actualCombat/model"
	"database/sql"
	"fmt"
	"github.com/satori/go.uuid"
	"log"
	"time"
)

/*

操作数据库创建文章，修改文章，删除文章，查看文章，等
*/
type IPostRepository interface {
	Create(post *model.Post) (err error)
	Updata(post *model.Post) (res sql.Result, err error)
	Select(field string, value interface{}) (exist bool, post *model.Post)
	List(pages, num int) (posts []*model.Post, count int, err error)
	Delete(post *model.Post) (err error)
}

//PostRepository 结构体
type PostRepository struct {
	Db *sql.DB
}

//NewPostRepository 创建一个postRepository实体
func NewPostRepository() IPostRepository {
	return PostRepository{Db: common.GetDb()}
}

//Select 文章查看
func (p PostRepository) Select(field string, value interface{}) (exist bool, post *model.Post) {
	sqlStr := fmt.Sprintf("select id,userid,classifyId,title,headImg,content,createAt,updataAt from post where %s=?", field)
	post = &model.Post{}
	_ = p.Db.QueryRow(sqlStr, value).Scan(&post.Id, &post.Userid, &post.ClassifyId, &post.Title, &post.HeadImg, &post.Content, &post.CreateAt, &post.UpdataAt)

	sqlStr2 := fmt.Sprintf("select id,name,createAt,updataAt from classify where id=?")
	classify := &model.Classify{}
	_ = p.Db.QueryRow(sqlStr2, post.ClassifyId).Scan(&classify.Id, &classify.Name, &classify.CreateAt, &classify.UpdataAt)

	post.Classify = classify
	if post.Userid != 0 {
		return true, post
	}
	return false, nil

}

//Create 创建文章
func (p PostRepository) Create(post *model.Post) (err error) {
	sqlStr := `insert post (id,userid,classifyId,title,headImg,content,createAt,updataAt) values(?,?,?,?,?,?,?,?)`
	uuid := uuid.NewV4()
	_, err = p.Db.Exec(sqlStr, uuid, post.Userid, post.ClassifyId, post.Title, post.HeadImg, post.Content, time.Now().Format("2006/01/02 15:04:05"), time.Now().Format("2006/01/02 15:04:05"))
	if err != nil {
		fmt.Println("创建文章失败，系统繁忙！", err)
		return err
	}
	_, posts := p.Select("id", uuid)
	post.Id = posts.Id
	post.Classify = posts.Classify
	post.CreateAt = posts.CreateAt
	post.UpdataAt = posts.UpdataAt
	return err
}

//Updata 修改文章
func (p PostRepository) Updata(post *model.Post) (res sql.Result, err error) {

	sqlStr := "UPDATE post SET title=?,headImg=?,content=?,updataAt=? WHERE id=?"
	res, err = p.Db.Exec(sqlStr, post.Title, post.HeadImg, post.Content, time.Now().Format("2006/01/02 15:04:05"), post.Id)
	if err != nil {
		fmt.Println("修改分类失败")
		return nil, err
	}
	_, posts := p.Select("id", post.Id)
	post.UpdataAt = posts.UpdataAt
	return res, nil
}

//List 分页
func (p PostRepository) List(pages, num int) (posts []*model.Post, count int, err error) {
	sqlStr := `SELECT p.id,p.userid,p.classifyId,p.title,p.headImg,p.content,p.createAt pc,p.updataAt pu,classify.id,classify.name,classify.createAt cc,classify.updataAt cu FROM post p INNER JOIN classify ON classify.id=p.classifyId ORDER BY p.createAt DESC LIMIT ?,?`
	posts = make([]*model.Post, 0)
	var classify model.Classify
	rows, err := p.Db.Query(sqlStr, (pages-1)*num, num)
	if err != nil {
		log.Println(err.Error())
		return nil, 0, err
	}
	defer rows.Close()
	var post model.Post
	var pCreateat, pUpdataAt, cCreateat, cUpdataAt string

	for rows.Next() {
		err := rows.Scan(&post.Id, &post.Userid, &post.ClassifyId, &post.Title, &post.HeadImg, &post.Content, &pCreateat, &pUpdataAt, &classify.Id, &classify.Name, &cCreateat, &cUpdataAt)
		//err := rows.Scan(&post.Id, &post.Userid, &post.ClassifyId, &post.Title, &post.HeadImg, &post.Content, &post.CreateAt, &post.UpdataAt, &classify.Name, &classify.CreateAt, &classify.UpdataAt)
		if err != nil {
			log.Println(err.Error())
			return nil, 0, err
		}

		post.CreateAt, _ = time.Parse("2006-01-02 15:04:05", pCreateat)
		post.UpdataAt, _ = time.Parse("2006-01-02 15:04:05", pUpdataAt)
		classify.CreateAt, _ = time.Parse("2006-01-02 15:04:05", cCreateat)
		classify.UpdataAt, _ = time.Parse("2006-01-02 15:04:05", cUpdataAt)
		posts = append(posts, &post)
		post.Classify = &classify
	}
	sqlStr2 := `SELECT count(*) FROM post`
	_ = p.Db.QueryRow(sqlStr2).Scan(&count)

	return posts, count, nil
}

//Delete 删除文章
func (p PostRepository) Delete(post *model.Post) (err error) {
	sqlStr := "DELETE from post WHERE id=?"
	_, err = p.Db.Exec(sqlStr, post.Id)
	if err != nil {
		log.Println(err.Error())
		return err
	}
	return nil
}
